#!/usr/bin/Rscript
##########################################################################################
# Social Media and Policy Responses to the COVID-19 Pandemic in Switzerland
##########################################################################################
# Description:
##########################################################################################
# Figure 3
##########################################################################################
# Contents
##########################################################################################
# 1) Dependencies
# 2) Data Import
# 3) Data Processing
# 4) Figure 3
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(ggplot2)
library(stringr)
library(forcats)
library(showtext)
library(stringr)
library(forcats)
##########################################################################################
# 2) Data Import
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)

setwd(pathName)
parent_path <- getwd()

# - load fonts used in plots
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

# - define a global seed (used in all scripts)
set.seed(2019)

# - load irf data 
final_input <- readRDS("../var/onetime-structural-shock-irfs-results_all_small_de_only_no_fb.RDS")

# - topic names for model selection
mod_name_nice <- c("Covid19", "Masks", "App", "All Three")

# - load ddl theme
suppressMessages(suppressWarnings(source('ggplot_theme_ddl.R')))
##########################################################################################
# 3) Data Processing
##########################################################################################
#-----------------------------------------------------------------------------------------
# - get data for responsiveness plot of all topics together
all_opics_all <- final_input[[4]]
all_opics_all$topic <- mod_name_nice[4]
all_opics_all <- all_opics_all %>% dplyr::filter(day %in% c(1,2,3,4,5,6,7,8,9))
all_opics_all <- all_opics_all %>% dplyr::filter(out %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) %>%
  dplyr::filter(cov %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) 

# - relabel the outcomes so they fit/look better in the plot
all_opics_all$out <- recode(as.character(all_opics_all$out),
                            `Media_SMD` = "Newspaper Articles",
                            `Politican_TW` = "Tweets by Politicians",
                            `Party_TW` = "Tweets by Parties",
                            `SnowBallers_TW` = "Tweets by informed Public")

# - relabel the covariates so they fit/look better in the plot
all_opics_all$cov <- recode(as.character(all_opics_all$cov),
                            `Media_TW` = "Newspapers on Twitter",
                            `Politican_TW` = "Tweets by Politicians",
                            `Party_TW` = "Tweets by Parties",
                            `SnowBallers_TW` = "Tweets by informed Public")

plot_resp_i <- all_opics_all %>%
  filter(day == 7 & data_type == "Effect of a one time 10 percentage point attention increase at day 0") %>%
  mutate(cov2 = cov) %>%
  mutate(out2 = out) %>%
  mutate(direction = paste0(cov2, " -> ", out2))

#-----------------------------------------------------------------------------------------
# - combine data from all four topics models
for(n in 1:(length(final_input)-1)){
  tmp <- final_input[[n]]
  tmp$topic <- mod_name_nice[n]
  
  if(n == 1){
    all_topics <- tmp
  } else if(n == 3){
    all_topics <- rbind(all_topics, tmp)
    all_topics <- all_topics %>% dplyr::filter(day %in% c(1,2,3,4,5,6,7,8,9))
    all_topics <- all_topics %>% dplyr::filter(out %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) %>% #"Media_FB", "Media_TW",  "Politcan_FB", "Party_FB"
      dplyr::filter(cov %in% c("Media_SMD", "Politican_TW", "Party_TW", "SnowBallers_TW")) #"Media_FB", "Media_TW", "Politican_FB", "Party_FB"
    # - relabel the outcomes so they fit/look better in the plot
    all_topics$out <- recode(as.character(all_topics$out),
                             Media_SMD = "Newspaper Articles",
                             Politican_TW = "Tweets by Politicians",
                             Party_TW = "Tweets by Parties",
                             SnowBallers_TW = "Attentive Public")
    
    # - relabel the covariates so they fit/look better in the plot
    all_topics$cov <- recode(as.character(all_topics$cov),
                             Media_SMD = "Newspaper Articles",
                             Politican_TW = "Tweets by Politicians",
                             Party_TW = "Tweets by Parties",
                             SnowBallers_TW = "Attentive Public")
    
  } else {
    all_topics <- rbind(all_topics, tmp)
    rm(tmp)
  }
}

all_topics$out <- recode(as.character(all_topics$out),
                           Media_SMD = "Newspaper Articles",
                           Politican_TW = "Tweets by Politicians",
                           Party_TW = "Tweets by Parties",
                           SnowBallers_TW = "Attentive Public")

# - relabel the covariates so they fit/look better in the plot
all_topics$cov <- recode(as.character(all_topics$cov),
                           Media_SMD = "Newspaper Articles",
                           Politican_TW = "Tweets by Politicians",
                           Party_TW = "Tweets by Parties",
                           SnowBallers_TW = "Attentive Public")

# - rename values for nicer plot of responsiveness plot per topic
plot_resp_ii <- all_topics %>%
  filter(day == 7 & data_type == "Effect of a one time 10 percentage point attention increase at day 0") %>%
  mutate(cov2 = cov) %>%
  mutate(out2 = out) %>%
  mutate(direction = paste0(cov2, " -> ", out2)) %>%
  mutate(TOPIC = str_to_upper(topic)) %>%
  mutate(topic = fct_relevel(topic, "Covid19", "Masks", "App")) %>%
  mutate(topic_rev = fct_relevel(topic, "App", "Masks", "Covid19"))
##########################################################################################
# 4) Figure 3
##########################################################################################
facet_names <- c(`Attentive Public` = "Effect of Tweets by the Attentive Public on:",
                 `Newspaper Articles` = "Effect of Newspaper Articles on:",
                 `Tweets by Parties` = "Effect of Tweets by Parties on:",
                 `Tweets by Politicians` = "Effect of Tweets by Politicians on:")

ggplot(data = plot_resp_ii) +
  aes(x = out, y = pe, ymin = lwr, ymax = upr, group = topic_rev, color = topic, shape = topic) +
  geom_linerange(size = 2.5, position = position_dodge(width = 0.55), alpha = 0.4) +  
  geom_point(position = position_dodge(width = 0.55), size = 3.5) +
  geom_hline(aes(yintercept = 0), color = "black", linetype = 2, alpha = 0.75) +
  coord_flip() +
  labs (title = "Attention responsiveness of parties, candidates, and newspapers",
        y = "Percentage points", x = "", color = "Topic:", shape = "Topic:") +
  scale_color_manual(labels = c("Covid19","Masks","App"), values = c("#DD2461", "#0072B2", "#999999")) + 
  scale_fill_manual(labels = c("Covid19","Masks","App"), values = c("#DD2461", "#0072B2", "#999999")) + 
  theme_light() + 
  ddl_theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank()) +
  facet_wrap(~cov, labeller = as_labeller(facet_names), ncol = 1, scales = "free_y") +
  theme(legend.position = "right", legend.title = element_text(size = 16),
        strip.background = element_blank(), strip.text = element_text(color = "black"),
        axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 20, color = "black"),  
        axis.text.y = element_text(hjust=0, size = 20, color = "black"),
        axis.title = element_text(size = 20, color = "black"),
        legend.text = element_text(size = 20, color = "black"),
        plot.title = element_blank(),
        strip.text.x = element_text(size = 20, color = "black"),
        plot.margin = unit(c(.5,.5,.5,.5), "cm"),
        panel.border = element_rect(color = "black", fill = NA, size = .5),
        legend.key.size = unit(2.5,"line")) +
  guides(color = guide_legend(override.aes = list(size=3)))

ggsave("../images/figure_three.pdf", width = 12, height = 18, device = cairo_pdf)

